package gridsoft.sapi.config;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

@Component
public class GlobalResultInterceptor implements RouterInterceptor {

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        //提示：这里和 doFilter 差不多...
        chain.doIntercept(ctx, mainHandler);
    }

    /**
     * 提交结果（ render 执行前调用）//不要做太复杂的事情
     */
    @Override
    public Object postResult(Context ctx, Object result) throws Throwable {
        if (result instanceof Throwable) {
            //异常类型，根据需要处理
            return result;
        } else if (result instanceof Result) {
            if (((Result<?>) result).getCode() > 0) {
                ctx.status(((Result<?>) result).getCode());
            }
            return result;
        } else if (result instanceof DownloadedFile) {
//            ctx.contentType("application/pdf");
            return result;
//            return new DownloadedFile(result, "demo.pdf", "application/pdf");
        } else {
            //例：{"name":"noear"} 变成 {"code":0,"msg":"","result":{"name":"noear"}}
            return Result.succeed(result);
        }
    }
}
